<template>
  <el-container style="padding: 20px">
    <!-- 概览卡片 -->
    <el-row :gutter="20">
      <el-col :span="8">
        <el-card shadow="hover">
          <div slot="header">
            <span>总销售额</span>
          </div>
          <div class="value-box">¥{{ totalSales.toFixed(2) }}</div>
          <div class="desc">已完成订单收入</div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover">
          <div slot="header">
            <span>总订单量</span>
          </div>
          <div class="value-box">{{ totalOrders }}</div>
          <div class="desc">含待付款订单</div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover">
          <div slot="header">
            <span>平均客单价</span>
          </div>
          <div class="value-box">¥{{ avgPrice.toFixed(2) }}</div>
          <div class="desc">已完成订单计算</div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 课程销售分析 -->
    <el-row :gutter="20" style="margin-top: 20px">
      <el-col :span="12">
        <el-card shadow="hover">
          <div slot="header">
            <span>课程销量排行（按订单数）</span>
          </div>
          <div class="chart-box">
            <div id="course-sales-chart" style="width: 100%; height: 300px"></div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card shadow="hover">
          <div slot="header">
            <span>课程销售额排行（按收入）</span>
          </div>
          <div class="chart-box">
            <div id="course-revenue-chart" style="width: 100%; height: 300px"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </el-container>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import * as echarts from 'echarts'
import { ElMessage } from 'element-plus'
// 模拟接口请求（实际替换为你的 API 调用）
import api from '@/api/order' 

// 响应式数据
const totalSales = ref(0)     // 总销售额
const totalOrders = ref(0)   // 总订单量
const avgPrice = ref(0)      // 平均客单价
const courseSalesData = ref([]) // 课程销量数据
const courseRevenueData = ref([]) // 课程销售额数据


// 模拟接口请求（实际开发替换为真实 API）
onMounted(async () => {
  try {
    // 1. 加载核心指标
    const [salesRes, ordersRes, priceRes] = await Promise.all([
      api.totalSales(),
      api.totalOrders(),
      api.averageOrderPrice()
    ]);
    totalSales.value = salesRes.data;
    totalOrders.value = ordersRes.data;
    avgPrice.value = priceRes.data;

    // 2. 加载课程销售数据
    courseSalesData.value = await (await api.courseSalesRanking()).data
    courseRevenueData.value = await (await api.courseSalesRankingByIncome()).data

    console.log("++++++++++++++++++++++++++++++++++++++++++++++++"+JSON.stringify((api.courseSalesRanking()).data))


    // 渲染图表
    renderCourseSalesChart()
    renderCourseRevenueChart()

  } catch (error) {
    ElMessage.error('数据加载失败：' + error.message)
  }
})

// 渲染课程销量柱状图
const renderCourseSalesChart = () => {
  const chartDom = document.getElementById('course-sales-chart')
  const myChart = echarts.init(chartDom)
  
  // 封装配置项（避免重复代码）
  const option = {
    xAxis: {
      type: 'category',
      data: courseSalesData.value.map(item => item.courseName)
    },
    yAxis: { type: 'value', name: '订单数' },
    series: [{
      name: '销量',
      type: 'bar',
      data: courseSalesData.value.map(item => item.salesCount),
      label: { show: true, position: 'top' }
    }],
    color: ['#2f4050']
  }

  myChart.setOption(option)

  // 关键：监听窗口变化，自动resize图表
  window.addEventListener('resize', () => {
    myChart.resize() // 触发ECharts重新计算容器宽度
  })
}

// 渲染课程销售额柱状图（同理添加resize监听）
const renderCourseRevenueChart = () => {
  const chartDom = document.getElementById('course-revenue-chart')
  const myChart = echarts.init(chartDom)
  
  const option = {
    xAxis: {
      type: 'category',
      data: courseRevenueData.value.map(item => item.courseName)
    },
    yAxis: { type: 'value', name: '销售额(元)' },
    series: [{
      name: '销售额',
      type: 'bar',
      data: courseRevenueData.value.map(item => item.salesAmount),
      label: { show: true, position: 'top' },
      color: ['#1f77b4']
    }]
  }

  myChart.setOption(option)

  window.addEventListener('resize', () => {
    myChart.resize()
  })
}

</script>

<style scoped>
.value-box {
  font-size: 24px;
  font-weight: bold;
  margin: 10px 0;
  color: #2f4050;
}
.desc {
  color: #999;
}
/* .chart-box {
  margin-top: 10px;
} */
/* 确保图表容器宽度随父元素变化 */
.chart-box {
  margin-top: 10px;
  width: 100% !important; 
  /* 如果是flex布局，可加flex: 1确保占满 */
}
</style>